import requests
import json


# 获取访问令牌
def get_access_token(app_id, app_secret):
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
    post_data = {"app_id": app_id, "app_secret": app_secret}
    r = requests.post(url, data=post_data)
    access_token = r.json().get("tenant_access_token")
    return access_token


# 写入数据到飞书表格
def append_to_sheet(app_id, app_secret, spreadsheet_token, sheet_id, date, revenue_type, platform, amount, account):
    access_token = get_access_token(app_id, app_secret)

    header = {
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {access_token}"
    }

    data_raw = {
        "valueRange": {
            "range": f"{sheet_id}!A:E",
            "values": [
                [
                    date,
                    revenue_type,
                    platform,
                    amount,
                    account
                ]
            ]
        }
    }

    url = f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheet_token}/values_append"
    r = requests.post(url, data=json.dumps(data_raw), headers=header)  # 请求写入
    return r.json()


# 示例调用
if __name__ == '__main__':
    app_id = "cli_a6f25692f223100b"
    app_secret = "qOIzUsJi0nym1jzPN5zxwcUCVd7u3vVy"
    spreadsheet_token = "CuLHsy1u5hMULRtw4TMcDCPUnGh"
    sheet_id = "263a37"

    date = "2023/12/25"
    revenue_type = "收入"
    platform = "微信"
    amount = "100"
    account = "帐号 老表max"

    response = append_to_sheet(app_id, app_secret, spreadsheet_token, sheet_id, date, revenue_type, platform, amount,
                               account)
    print(response.get("msg"))  # 输出判断写入是否成功
